app.controller("contractUserCtrl", function ($scope,$interval, $http, contractUserService) {

    //----------分页参数------------
    $scope.pageRowSize = 10;
    $scope.curPage = 1;

    //-----------------------------

    $scope.object = {};
    $scope.formMode = false;
    $scope.errors = {};

    $scope.isSuperAdmin = false;

    //--------------初始化菜单---------------
    $scope.initMenu = function () {
        showSecondMenu('billingManage');
        selectSecondMenu('contractUserManage');
    }
    $scope.initMenu();

    //---------------错误信息--------------
    $scope.requestError = function () {
        $scope.errorMessage = "unknown error!"
    };

    $scope.init = function () {
        //默认加载合同用户Tree结构
        $scope.getContractUserTree();
        var span_superAdmin = $("#span_superAdmin").text();
        if(span_superAdmin == "true"){
            $scope.isSuperAdmin = true;
        }
    };

    //编辑合同用户
    $scope.editContractUser = function () {
        //非空判断
        if (NullOrUndefined($scope.contractUserObject.userAbbrev)) {
            promptMsg("请输入用户简称！")
            return false;
        }
        if (NullOrUndefined($scope.contractUserObject.userType) || ($scope.contractUserObject.userType == 0)) {
            promptMsg("请选择用户类型！")
            return false;
        }

        contractUserService.editContractUser({
            action: 'editContractUser',
            contractUserId: $scope.contractUserObject.contractUserId,
            userAbbrev: $scope.contractUserObject.userAbbrev,
            userFullname : $scope.contractUserObject.userFullname,
            userType : $scope.contractUserObject.userType,
            personLiable : $scope.contractUserObject.personLiable,
            mobilephone : $scope.contractUserObject.mobilephone,
            telephone : $scope.contractUserObject.telephone,
            mail : $scope.contractUserObject.mail,
            postcode : $scope.contractUserObject.postcode,
            address : $scope.contractUserObject.address,
            billingRuleId : $scope.contractUserObject.billingRuleId
        }, function (data) {
            if (data.status == "SUCCESS") {
                promptMsg(data.data.msg);
                $("#editContractUserModal").modal("hide");    //关闭编辑界面
                $scope.contractUserId = data.data.contractUserId;

                $scope.init();    //刷新Tree
                setTimeout(function () {
                    //ztree模拟onClick点击事件（传入节点id，不是页面元素id）
                    $scope.imitateZTreeOnClick($scope.contractUserId);
                    $scope.findContractUsers();  //刷新合同用户
                }, 100);
            } else {
                promptMsg(data.errorReason);
            }
        }, $scope.requestError());
    }

    // 加载合同用户信息
    $scope.findContractUsers = function(){
        $.fn.jqLoading({ height: 100, width: 240, text: "查询中，请稍等...." });
        contractUserService.findContractUser({
            action: 'findContractUser',
            contractUserId: $scope.contractUserId
        }, function (data) {
            $.fn.jqLoading("destroy");
            if (data.status == 'SUCCESS'){
                $scope.contractUserEntityVO = data.data.contractUserEntityVO;
                //显示DIV
                $("#div_billingrule_table").show();
            } else {
                promptMsg(data.data.msg);
            }
        }, $scope.requestError());
    }

    //关闭编辑合同用户窗口
    $scope.closeContractUserModal = function(){
        //重新加载合同用户信息，避免显示用户已编辑的信息（新增不需要）
        if(!NullOrUndefined($scope.contractUserObject.contractUserId)){
            $scope.findContractUsers();
        }
        $("#editContractUserModal").modal("hide");
    };

    //删除合同用户
    $scope.deleteContractUser = function () {
        if($scope.contractUserEntityVO == null){
            promptMsg("请选择待删除的合同用户！");
            return;
        }

        function confirmSubmit() {
            contractUserService.deleteContractUser({
                action : 'deleteContractUser',
                contractUserId :  $scope.contractUserEntityVO.contractUserId
            }, function (data) {
                if (data.status == "SUCCESS") {
                    $scope.contractUserEntityVO = null;
                    promptMsg(data.data.msg);
                } else {
                    promptMsg(data.errorReason);
                }
                //重新加载合同用户Tree
                $scope.init();
            }, $scope.requestError());
        }

        confirmMsg("确定删除这个合同用户吗？", confirmSubmit, null);
    };

    //----------------------文件夹树结构---------------------------------------------
    var setting = {
        view: {
            showIcon: false    //不显示图标
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: zTreeOnClick
        }
    };

    //ztree模拟onClick点击事件（传入节点id，不是页面元素id）
    $scope.imitateZTreeOnClick = function (nodeId) {
        var tObj = $.fn.zTree.getZTreeObj("contractUserTree");
        // 根据树id来获取节点，这里treeId是树对象里节点id，不是页面元素id
        var selectedNode = tObj.getNodeByParam("id", nodeId);
        // 根据节点，默认选中节点
        tObj.selectNode(selectedNode);
    };

    //获取合同用户Tree
    $scope.getContractUserTree = function () {
        contractUserService.getContractUserTree({
            action: 'getContractUserTree'
        }, function (data) {
            var treeObj = $.fn.zTree.init($("#contractUserTree"), setting, data);
        }, $scope.requestError());
    };

    //合同用户树状图单击事件
    function zTreeOnClick(event, treeId, treeNode) {
        //树状节点层级
        $scope.treeLevel = treeNode.level;
        if($scope.treeLevel == 0){   //不处理根节点的单击事件
            $scope.contractUserEntityVO = null;
            //获取根节点类型：“航司”、“机场”
            $scope.userType = treeNode.id;
            //显示DIV
            $("#div_billingrule_table").hide();
        }else {
            $scope.userType = "";
            $scope.contractUserId = treeNode.id;
            //加载合同用户信息
            $scope.findContractUsers();
        }
    }

    //编辑合同用户
    $scope.toEditContractUser = function (operate) {
        if(operate == "2"){
            if($scope.contractUserEntityVO == null){
                promptMsg("请选择待编辑的合同用户！");
                return;
            }
            $scope.contractUserObject = $scope.contractUserEntityVO;
            $scope.contractUserObject.userType = $scope.contractUserObject.userType + "";
        }else{
            $scope.contractUserObject = {};
            //【合同用户管理】选中合同用户类型后点击新增，需要把类型带进去
            if(NullOrUndefined($scope.userType)){
                $scope.contractUserObject.userType = "0";
            }else {
                if($scope.userType == "AIRLINES"){
                    $scope.contractUserObject.userType = "2";
                }else {
                    $scope.contractUserObject.userType = "1";
                }
            }
        }
        //模态框居中： 将事件监听的事件改成show.bs.modal 即可解决
        $('#editContractUserModal').on('show.bs.modal', centerModals("editContractUserModal"));
        $("#editContractUserModal").modal({
            backdrop: "static",//点击空白处不关闭对话框
            keyboard:false // 按esc键盘不关闭
        });
    }

    //计费范围
    $scope.toBillingRange = function () {
        if($scope.contractUserEntityVO == null){
            promptMsg("请选择合同用户！");
            return;
        }
        //航司
        contractUserService.findAirLines({
            action : 'findAirLines',
            contractUserId :  $scope.contractUserEntityVO.contractUserId
        }, function (data) {
            $scope.airlinesEntityVOList = data.data.airlinesEntityVOList;
        }, $scope.requestError());
        //机场
        contractUserService.findAirports({
            action : 'findAirports',
            contractUserId :  $scope.contractUserEntityVO.contractUserId
        }, function (data) {
            $scope.airportEntityVOList = data.data.airportEntityVOList;
        }, $scope.requestError());

        //模态框居中： 将事件监听的事件改成show.bs.modal 即可解决
        $('#billingRangeModal').on('show.bs.modal', centerModals("billingRangeModal"));
        $("#billingRangeModal").modal({
            backdrop: "static",//点击空白处不关闭对话框
            keyboard:false // 按esc键盘不关闭
        });
    }
    //编辑计费范围
    $scope.editBillingRange = function () {
        //判断是否勾选了机场
        if ($('input[name="airportIds"]:checked').val() == null || $('input[name="airportIds"]:checked').val() == "") {
            promptMsg("请选择机场！")
            return false;
        }
        //判断是否勾选了航司
        if ($('input[name="airlineIds"]:checked').val() == null || $('input[name="airlineIds"]:checked').val() == "") {
            promptMsg("请选择航司！")
            return false;
        }
        //获取已选中的机场ids，并赋值给$scope.contractUserEntityVO.airportIds传入后台保存
        var selectedAirportIds = "";
        $('input[name="airportIds"]:checked').each(function (i) {
            var id = $(this).attr("value");
            if (i != 0) {
                selectedAirportIds += "," + id;
            } else {
                selectedAirportIds += id;
            }
        });
        $scope.contractUserEntityVO.airportIds = selectedAirportIds;

        //获取已选中的航司ids，并赋值给$scope.contractUserEntityVO.airlineIds传入后台保存
        var selectedAirlineIds = "";
        $('input[name="airlineIds"]:checked').each(function (i) {
            var id = $(this).attr("value");
            if (i != 0) {
                selectedAirlineIds += "," + id;
            } else {
                selectedAirlineIds += id;
            }
        });
        $scope.contractUserEntityVO.airlineIds = selectedAirlineIds;

        //计费范围
        contractUserService.editBillingRange({
            action : 'editBillingRange',
            contractUserId :  $scope.contractUserEntityVO.contractUserId,
            airportIds :  $scope.contractUserEntityVO.airportIds,
            airlineIds :  $scope.contractUserEntityVO.airlineIds
        }, function (data) {
            if (data.status == "SUCCESS") { //编辑成功，关闭界面，刷新列表
                promptMsg(data.data.msg);
                //关闭计费范围窗口
                $scope.closeBillingRangeModal();
            }else {
                promptMsg(data.errorReason);
            }
        }, $scope.requestError());
    }

    //计费规则
    $scope.toBillingRule = function () {
        if($scope.contractUserEntityVO == null){
            promptMsg("请选择合同用户！");
            return;
        }
        //计费规则
        contractUserService.findBillingRules({
            action : 'findBillingRules',
            contractUserId :  $scope.contractUserEntityVO.contractUserId
        }, function (data) {
            $scope.billingRuleEntityVOList = data.data.billingRuleEntityVOList;
        }, $scope.requestError());

        //模态框居中： 将事件监听的事件改成show.bs.modal 即可解决
        $('#billingRuleModal').on('show.bs.modal', centerModals("billingRuleModal"));
        $("#billingRuleModal").modal({
            backdrop: "static",//点击空白处不关闭对话框
            keyboard:false // 按esc键盘不关闭
        });
    }

    //编辑计费规则
    $scope.editBillingRule = function () {
        //判断是否勾选了计费规则
        var billingRuleId = $('input[name="billingRuleIds"]:checked').val();
        if (NullOrUndefined(billingRuleId)) {
            promptMsg("请选择计费规则！")
            return false;
        }
        //计费规则
        contractUserService.editBillingRule({
            action : 'editBillingRule',
            contractUserId :  $scope.contractUserEntityVO.contractUserId,
            billingRuleId :  billingRuleId
        }, function (data) {
            if (data.status == "SUCCESS") { //编辑成功，关闭界面，刷新列表
                promptMsg(data.data.msg);
                //关闭计费规则窗口
                $scope.closeBillingRuleModal();
            }else {
                promptMsg(data.errorReason);
            }
        }, $scope.requestError());
    }

    //关联用户Tree设置
    var associatedUsersSetting = {
        check: {
            enable: true,//显示复选框
            chkboxType: { "Y":"ps", "N":"ps"}
        },
        data: {
            simpleData: {
                enable: true
            }
        }
    };

    //关联用户
    $scope.toAssociatedUsers = function () {
        if($scope.contractUserEntityVO == null){
            promptMsg("请选择合同用户！");
            return;
        }
        //用户
        contractUserService.getAssociatedUsersTree({
            action: 'getAssociatedUsersTree',
            contractUserId :  $scope.contractUserEntityVO.contractUserId
        }, function (data) {
            var treeObj = $.fn.zTree.init($("#associatedUsersTree"), associatedUsersSetting, data);
            //滚动条回到顶端
            $("#loadsheetstaff").animate({scrollTop:0},200);

            //模态框居中： 将事件监听的事件改成show.bs.modal 即可解决
            $('#associatedUsersModal').on('show.bs.modal', centerModals("associatedUsersModal"));
            $("#associatedUsersModal").modal({
                backdrop: "static",//点击空白处不关闭对话框
                keyboard:false // 按esc键盘不关闭
            });
        }, $scope.requestError());


    }
    //编辑关联用户
    $scope.editAssociatedUsers = function () {
        var treeObj = $.fn.zTree.getZTreeObj("associatedUsersTree"),
            nodes = treeObj.getCheckedNodes(true),
            v = "";
        $scope.associatedUserIds = v;
        var obj;
        for(var i = 0;i < nodes.length;i++){
            obj = nodes[i];
            //判断父节点是否有子节点（部门下是否有用户）
            if(obj.isParent && (obj.children == null || obj.children.length == null || obj.children.length == 0)){
                promptMsg(obj.name + "部门下无用户，请重新选择！");
                return false;
            }
            //如果不是父节点
            if(!obj.isParent){
                if(v != ""){
                    v += ",";
                }
                v += obj.id;
                $scope.associatedUserIds = v;
            }
        }

        //关联用户
        contractUserService.editAssociatedUsers({
            action : 'editAssociatedUsers',
            contractUserId :  $scope.contractUserEntityVO.contractUserId,
            associatedUserIds :  $scope.associatedUserIds
        }, function (data) {
            if (data.status == "SUCCESS") { //编辑成功，关闭界面，刷新列表
                promptMsg(data.data.msg);
                //关闭关联用户窗口
                $scope.closeAssociatedUsersModal();
            }else {
                promptMsg(data.errorReason);
            }
        }, $scope.requestError());
    }

    //关闭关联用户窗口
    $scope.closeAssociatedUsersModal = function(){
        $("#associatedUsersModal").modal("hide");
    };

    //关闭计费范围窗口
    $scope.closeBillingRangeModal = function(){
        $("#billingRangeModal").modal("hide");
    };

    //关闭计费规则窗口
    $scope.closeBillingRuleModal = function(){
        $("#billingRuleModal").modal("hide");
    };

    //全选航司
    $scope.checkAllAirlines = function(){
        if($("#chk_checkAllAirlines").prop("checked")){
            //全选航司
            $('input[name="airlineIds"]').prop("checked", true);
            //取消反选选中
            $("#chk_inverseCheckAllAirlines").prop("checked", false);
        }else {
            //全不选航司
            $('input[name="airlineIds"]').prop("checked", false);
        }
    };
    //反选航司
    $scope.inverseCheckAllAirlines = function(){
        if($("#chk_inverseCheckAllAirlines").prop("checked")){
            //反选
            $('input[name="airlineIds"]').each(function (i) {
                var checked = $(this).prop("checked");
                $(this).prop("checked", !checked);
            });
            //取消全选选中
            $("#chk_checkAllAirlines").prop("checked", false);
        }
    };

    //全选机场
    $scope.checkAllAirports = function(){
        if($("#chk_checkAllAirports").prop("checked")){
            //全选机场
            $('input[name="airportIds"]').prop("checked", true);
            //取消反选选中
            $("#chk_inverseCheckAllAirports").prop("checked", false);
        }else {
            //全不选机场
            $('input[name="airportIds"]').prop("checked", false);
        }
    };
    //反选机场
    $scope.inverseCheckAllAirports = function(){
        if($("#chk_inverseCheckAllAirports").prop("checked")){
            //反选
            $('input[name="airportIds"]').each(function (i) {
                var checked = $(this).prop("checked");
                $(this).prop("checked", !checked);
            });
            //取消全选选中
            $("#chk_checkAllAirports").prop("checked", false);
        }
    };
});